package cn.tom.tompicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.tom.tompicturebackend.constant.UserConstant;
import cn.tom.tompicturebackend.exception.BusinessException;
import cn.tom.tompicturebackend.exception.ErrorCode;

import cn.tom.tompicturebackend.model.dto.user.UserQueryRequest;
import cn.tom.tompicturebackend.model.enums.UserRoleEnum;
import cn.tom.tompicturebackend.model.vo.LoginUserVo;

import cn.tom.tompicturebackend.model.vo.UserVo;
import cn.tom.tompicturebackend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.tom.tompicturebackend.model.entity.User;
import cn.tom.tompicturebackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.tom.tompicturebackend.constant.UserConstant.USER_LOGIN_STATE;

/**

* @author tom
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {


    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword)
    {
        if(StrUtil.hasEmpty(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");

        }
        if(userAccount.length()<3){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        if(userPassword.length()<6||checkPassword.length()<6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不能小于8位");
        }
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }

        //2.检查是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = this.baseMapper.selectCount(queryWrapper);

        //3.加密
        String encryptPassword = getEncryptPassword(userPassword);

        //4.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());

        boolean saveResult = this.save(user);
        if(!saveResult){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败");
        }
        return user.getId();
    }

    /**
     * 登录
     * @param userAccount
     * @param userPassword
     * @param request
     * @return
     */
    @Override
    public LoginUserVo userLogin(String userAccount, String userPassword, HttpServletRequest request)
    {
        //1、检验
        if(StrUtil.hasBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码不能为空");
        }
        if(userAccount.length() < 3 || userPassword.length() < 6){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码格式错误");
        }
        if(userPassword.length()<8){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不能小于8位");
        }
        //2、加密
        String encryptPassword = getEncryptPassword(userPassword);
        //3、查询
        QueryWrapper<User> eq = new QueryWrapper<User>().eq("userAccount", userAccount).eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(eq);
        //4、判断
        if(user == null){
            log.info("用户名或密码错误");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名或密码错误");
        }
        //5、记录用户状态
        request.getSession().setAttribute(USER_LOGIN_STATE,user);

        return this.getLoginUserVo(user);
    }

    /**
     * 加密
     * @param userPassword
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword)
    {
        //盐
        final String SALT = "tom";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 用户信息脱敏
     * @param user
     * @return
     */
    @Override
    public LoginUserVo getLoginUserVo(User user)
    {
        if(user == null){
            return null;
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        BeanUtil.copyProperties(user,loginUserVo);
        return loginUserVo;
    }

    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @Override
    public User getLoinUser(HttpServletRequest request)
    {
        //判断是否登录
        Object user =  request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) user;

        if(currentUser == null || currentUser.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        long userId = currentUser.getId();
        //查询用户信息
        currentUser = this.getById(userId);
        if(currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return currentUser;
    }

    @Override
    public boolean userLogout(HttpServletRequest request)
    {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        if(attribute == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public UserVo getUserVo(User user)
    {
        if(user == null){
            return null;
        }
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user,userVo);

        return userVo;
    }

    @Override
    public List<UserVo> getUserVoList(List<User> userList)
    {
        if(CollUtil.isEmpty(userList)){
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVo).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQuryRequest)
    {
        if(userQuryRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        Long id = userQuryRequest.getId();
        String userAccount = userQuryRequest.getUserAccount();
        String userName = userQuryRequest.getUserName();

        String userProfile = userQuryRequest.getUserProfile();
        String userRole = userQuryRequest.getUserRole();
        int current = userQuryRequest.getCurrent();
        int pageSize = userQuryRequest.getPageSize();
        String sortField = userQuryRequest.getSortField();
        String sortOrder = userQuryRequest.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userAccount), "user_account", userAccount);
        queryWrapper.eq(StrUtil.isNotBlank(userName), "user_name", userName);
        queryWrapper.eq(StrUtil.isNotBlank(userProfile), "user_profile", userProfile);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "user_role", userRole);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField),sortOrder.equals("ascend"),sortField);
        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        return user !=null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否已经登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库中查询（追求性能的话可以注释，直接返回上述结果）
        Long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

}




